<?php namespace Phpcmf\Controllers\Api;

// 文件操作
class File extends \Phpcmf\Common
{

    private $siteid;

    public function __construct(...$params)
    {
        parent::__construct(...$params);
        $this->siteid = max(intval($_GET['siteid']), 1);
    }

    // 验证上传权限，并获取上传参数
    private function _get_upload_params() {

        if (!$this->member) {
            $this->_json(0, dr_lang('请登录之后再操作'));
        }

        // 验证用户权限
        $rt = \Phpcmf\Service::M('Attachment')->check($this->member, $this->siteid);
        !$rt['code'] && exit(json_encode($rt));

        if ($this->member['is_admin']) {
            // 管理员不验证字段
            $p = dr_string2array(dr_authcode(\Phpcmf\Service::L('Input')->get('p'), 'DECODE'));
            !$p && $this->_json(0, dr_lang('字段参数有误'));
            return $p;
        }

        $fid = (int)\Phpcmf\Service::L('Input')->get('fid');
        $field = \Phpcmf\Service::C()->get_cache('table-field', $fid);
        if (!$field) {
            $this->_json(0, dr_lang('上传字段未定义'));
        }

        return [
            'size' => intval($field['setting']['option']['size']),
            'exts' => $field['setting']['option']['ext'],
            'count' => max(1, (int)$field['setting']['option']['count']),
            'attachment' => $field['setting']['option']['attachment'],
        ];
    }

    /**
     * 文件上传
     */
    public function upload_file() {

        $p = $this->_get_upload_params();
        $rt = \Phpcmf\Service::L('upload')->upload_file([
            'path' => '',
            'form_name' => 'file_data',
            'file_exts' => @explode(',', $p['exts']),
            'file_size' => (int)$p['size'] * 1024 * 1024,
            'attachment' => \Phpcmf\Service::M('Attachment')->get_attach_info((int)$p['attachment']),
        ]);
        !$rt['code'] && exit(json_encode($rt));

        // 附件归档
        $data = \Phpcmf\Service::M('Attachment')->save_data($rt['data']);
        !$data['code'] && exit(json_encode($data));

        // 上传成功
        if (IS_API_HTTP) {
            $data['data'] = [
                'id' => $data['code'],
                'url' => $rt['data']['url'],
            ];
            exit(json_encode($data));
        } else {
            exit(json_encode(['code' => 1, 'msg' => dr_lang('上传成功'), 'id' => $data['code'], 'info' => $rt['data']]));
        }

    }

    /**
     * 输入一个附件
     */
    public function input_file_url() {


        $p = $this->_get_upload_params();

        if (IS_AJAX_POST) {

            $post = \Phpcmf\Service::L('Input')->post('data');
            empty($post['url']) && $this->_json(0, dr_lang('文件地址不能为空'));

            if ($post['down']) {
                // 验证用户权限
                $rt = \Phpcmf\Service::M('Attachment')->check($this->member, $this->siteid);
                !$rt['code'] && exit(json_encode($rt));

                // 下载远程文件
                $rt = \Phpcmf\Service::L('upload')->down_file([
                    'url' => $post['url'],
                    'attachment' => \Phpcmf\Service::M('Attachment')->get_attach_info((int)$p['attachment']),
                ]);
                !$rt['code'] && exit(json_encode($rt));

                // 附件归档
                $att = \Phpcmf\Service::M('Attachment')->save_data($rt['data']);
                !$att['code'] && exit(json_encode($att));

                $data = [
                    'id' => $att['code'],
                    'name' => $post['name'],
                    'file' => $rt['data']['file'],
                    'preview' => $rt['data']['preview'],
                    'upload' => '<input type="file" name="file_data"></button>',
                ];
            } else {
                $data = [
                    'id' => $post['url'],
                    'name' => $post['name'] ? $post['name'] : '',
                    'file' => $post['url'],
                    'preview' => dr_file_preview_html($post['url']),
                    'upload' => '',
                ];
            }

            $this->_json(1, dr_lang('上传成功'), $data);
            exit;
        }

        \Phpcmf\Service::V()->admin();
        \Phpcmf\Service::V()->assign([
            'one' => \Phpcmf\Service::L('Input')->get('one'),
            'file' => \Phpcmf\Service::L('Input')->get('file'),
            'name' => \Phpcmf\Service::L('Input')->get('name'),
            'form' => dr_form_hidden()
        ]);
        \Phpcmf\Service::V()->display('api_upload_url.html');
        exit;
    }

    /**
     * 未使用的附件
     */
    public function input_file_unused() {


        $p = $this->_get_upload_params();

        $c = (int)\Phpcmf\Service::L('Input')->get('ct'); // 当已有数量
        $ct = (int)$p['count']; // 可上传数量

        if (IS_AJAX_POST) {
            $ids = \Phpcmf\Service::L('Input')->get_post_ids();
            !$ids && $this->_json(0, dr_lang('至少要选择一个文件'));
            count($ids) > $ct - $c && $this->_json(0, dr_lang('选择文件过多'));
            $list = [];
            $temp = \Phpcmf\Service::M()->table('attachment_unused')->where('uid', $this->uid)->where_in('id', $ids)->getAll();
            foreach ($temp as $t) {
                $list[] = [
                    'id' => $t['id'],
                    'name' => $t['filename'],
                    'file' => $t['attachment'],
                    'preview' => dr_file_preview_html(dr_get_file_url($t)),
                    'upload' => '<input type="file" name="file_data"></button>',
                ];
            }

            $data = [
                'count' => count($ids),
                'result' => $list,
            ];
            $this->_json(1, dr_lang('已选择%s个文件', $data['count']), $data);
        }

        $exts = dr_safe_replace($p['exts']);
        \Phpcmf\Service::V()->admin();
        \Phpcmf\Service::V()->assign([
            'form' => dr_form_hidden(),
            'list' => $exts ? \Phpcmf\Service::M()->table('attachment_unused')->where('uid', $this->uid)->where_in('fileext', explode(',', $exts))->order_by('id desc')->getAll(30) : \Phpcmf\Service::M()->table('attachment_unused')->order_by('id desc')->getAll(30),
        ]);
        \Phpcmf\Service::V()->display('api_upload_unused.html');exit;
    }

    /**
     * 删除文件
     */
    public function file_delete() {

        $rt = \Phpcmf\Service::M('Attachment')->file_delete(
            (int)$this->member['id'],
            (int)\Phpcmf\Service::L('Input')->get('id')
        );

        $this->_json($rt['code'], $rt['msg']);
    }

    /**
     * 下载文件
     */
    public function down() {

        // 判断下载权限
        if (!$this->_member_auth_value($this->member_authid, 'downfile')) {
            $this->_msg(0, dr_lang('您所在用户组不允许下载附件'));
        }

        // 读取附件信息
        $id = urldecode(\Phpcmf\Service::L('input')->get('id'));
        if (is_numeric($id)) {
            // 表示附件id
            $info = $this->get_attachment($id);
            if (!$info) {
                // 不存在
                $this->_msg(0, dr_lang('附件不存在'));
            } elseif (is_file($info['file'])) {
                $rt = $this->response->download($info['filename'].'.'.$info['fileext'], file_get_contents($info['file']));
                if (!$rt) {
                    $this->_msg(0, dr_lang('文件不存在'));
                }
                exit;
            } elseif (strpos($info['file'], 'http') === 0) {
                // 远程附件
                dr_redirect($info['file']);
            } else {
                $this->_msg(0, dr_lang('附件异常'));
            }
        } else {
            $info = dr_file($id);
            if (!$info) {
                // 不存在
                $this->_msg(0, dr_lang('附件不存在'));
            }
            dr_redirect($info);
        }

        exit;
    }



}
